package geektime.jvm;

import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;

import java.io.IOException;

public class CustomClassWriter {
    private ClassReader reader;
    private ClassWriter writer;
    private PublicizeMethodAdapter pubMethodAdapter;
    private String className;

    // 根据className提供的构造方法
    public CustomClassWriter(String className) {
        try {
            reader = new ClassReader(className);
            writer = new ClassWriter(reader, 0);
            this.pubMethodAdapter = new PublicizeMethodAdapter(writer);
            this.className = className;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 将某个方法公共化，并返回重新构建编译后的类的字节码
    public byte[] publicizeMethod(){
        reader.accept(pubMethodAdapter, 0);
        return writer.toByteArray();
    }

    public CustomClassWriter(byte[] classFile) {
        reader = new ClassReader(classFile);
        writer = new ClassWriter(reader,0);
    }

    public static void main(String[] args) {
        CustomClassWriter originCcw = new CustomClassWriter("java.lang.Integer");
        byte[] newClassFile = originCcw.publicizeMethod();
        CustomClassWriter newCcw = new CustomClassWriter(newClassFile);
    }

}
